/* 
 * 创建日期 2016-02-19
 *
 * 成都澳乐科技有限公司
 * 电话：028-85253121 
 * 传真：028-85253121
 * 邮编：610041 
 * 地址：成都市武侯区航空路6号丰德国际C3
 * 版权所有
 */
package com.itrip.log.module.task;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.itrip.log.module.db.domain.MethodAlarmBean;

/**
 * 告警任务<br>
 * author:jeff.cao@aoliday.com date:2016年3月7日
 */
@Component("AlamrmTask")
public class AlamrmTask extends BaseTask {

	private static Logger logger = LoggerFactory.getLogger(AlamrmTask.class);
	private String templateCount = "[%s_%s]Dubbo服务[%s.%s][%s]秒内调用[%s]次<br>\n";
	private String utemplateCount = "[%s_%s]Url[%s][%s]秒内调用[%s]次<br>\n";
	private String template = "[%s_%s]Dubbo服务[%s.%s]平均耗时[%s]\n";
	private String utemplate = "[%s_%s]Url:[%s]耗时过高[%s]<br>\n";

	@Scheduled(cron = "30 0/3 * * * *")
	public void run() {
		try {
			long now = System.currentTimeMillis();
			List<MethodAlarmBean> malarms = daoTemplate.getListByMap("MethodAlarmBean", null);
			if (malarms.size() > 0) {
				testMethodHasAlarm(malarms, now);
				testURLHasAlarm(malarms, now);
				logger.info("succcess to execute alamrmTask");
			} else {
				logger.debug("MethodAlarm is empty");
			}
		} catch (Exception e) {
			logger.error("error:", e);
		} 
	}

	private void testURLHasAlarm(List<MethodAlarmBean> malarms, long now) throws SQLException {
		for (MethodAlarmBean alarm : malarms) {
			if (!alarm.getType().equals("url")) {
				continue;
			}
			Map<String, Object> pa = new HashMap<String, Object>();
			pa.put("start", (now - alarm.getPeriod() * 1000) / 60000);
			pa.put("method", alarm.getMethod());
			pa.put("proc", alarm.getProc());

			List<Map<String, Object>> selectList = daoTemplate.selectList("common.queryAlarm", pa);
			for (Map<String, Object> item : selectList) {
				if(item==null)continue;
				String host = (String) item.get("host");
				String proc = (String) item.get("proc");
				float times = (float) item.get("avgt");
				int calls = (int) item.get("calls");
				if (times > alarm.getTimeThreshold()) {
					String info = String.format(utemplate, host, proc, alarm.getMethod(), times);
					StringBuffer sbInfo = new StringBuffer(info);
					mailQueue.addEmailTask(alarm.getEmailGroup(), proc, sbInfo, alarm.getMethod());
				} else if (calls > alarm.getRequestCount()) {
					String info = String.format(utemplateCount, host, proc, alarm.getMethod(), alarm.getPeriod(), calls);
					StringBuffer sbInfo = new StringBuffer(info);
					mailQueue.addEmailTask(alarm.getEmailGroup(), proc, sbInfo, alarm.getMethod());
				}
			}
		}
	}

	private void testMethodHasAlarm(List<MethodAlarmBean> malarms, long now) throws SQLException {
		for (MethodAlarmBean alarm : malarms) {
			if (alarm.getType().equals("url")) {
				continue;
			}
			
			Map<String, Object> pa = new HashMap<String, Object>();
			pa.put("start", (now - alarm.getPeriod() * 1000) / 60000);
			pa.put("method", alarm.getMethod());
			pa.put("api", alarm.getService());
			pa.put("proc", alarm.getProc());

			List<Map<String, Object>> selectList = daoTemplate.selectList("common.queryAlarm", pa);
			for (Map<String, Object> item : selectList) {
				if(item==null)continue;
				String service = (String) item.get("service");
				String method = (String) item.get("method");
				String host = (String) item.get("host");
				String proc = (String) item.get("proc");
				float times = (float) item.get("avgt");
				int calls = (int) item.get("calls");
				
				if (times > alarm.getTimeThreshold()) {
					String info = String.format(template, host, proc, service, method, times);
					StringBuffer sbInfo = new StringBuffer(info);
					mailQueue.addEmailTask(alarm.getEmailGroup(), proc, sbInfo, alarm.getMethod());
				} else if (calls > alarm.getRequestCount()) {
					String info = String.format(templateCount, host, proc, service, method, alarm.getPeriod(), calls);
					StringBuffer sbInfo = new StringBuffer(info);
					mailQueue.addEmailTask(alarm.getEmailGroup(), proc, sbInfo, alarm.getMethod());
				}
			}
		}
	}
}
